package com.freejava.jdbctest.dao;

import com.freejava.jdbctest.entities.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

@Repository
public class BookDao {
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 获取所有书
    // 写代码的时候，要会参考源码（api），连蒙带猜的写
    public List<Book> getAll() {
//        String param = "2";
//        String sql = "select * from books where id > ? and title = ?";
        String sql = "select * from books";
//        Object[] objArr = {param, "hello"};
//        return jdbcTemplate.query(sql, objArr, new BeanPropertyRowMapper<Book>(Book.class));
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Book>(Book.class));
    }

    // 获取单本书的数据
    public Book getBookById(int id) {
        try {
            // queryForObject 表示返回一个结果
            // 如果查询不到结果，会报错，而不是返回null，如果想要返回null，需要我们自己捕获异常来处理
            return jdbcTemplate.queryForObject("select * from books where id= ?",
                    new BeanPropertyRowMapper<>(Book.class), id);
        } catch (EmptyResultDataAccessException e) {
            return null; // 或者抛出自定义异常，视情况而定
        }
    }

    // 新增一本书
    public int addBook(Book book) {
        return jdbcTemplate.update("insert into books(title, price, created) values(?, ?, ?)",
                book.getTitle(), book.getPrice(), book.getCreated());
    }


    // 更新书籍信息
    public int update(Book book) {
        return jdbcTemplate.update("UPDATE books set title=?, price=? WHERE id=?",
                book.getTitle(), book.getPrice(), book.getId());
    }

    // 删除书籍信息
    public int delete(int id) {
        return jdbcTemplate.update("delete from books where id = ?", id);
    }

    // 批量更新书籍
    public int[] updateBatch(List<Book> books) {

        // 在方法里需要一个接口
        // 1.传递一个接口的实现类
        // 2.使用匿名内部类的方式
        return jdbcTemplate.batchUpdate("update books set title = ?, price = ? where id = ?",
                new BatchPreparedStatementSetter() {
                    @Override
                    public void setValues(PreparedStatement ps, int index) throws SQLException {
                        Book book = books.get(index);
                        ps.setString(1, book.getTitle());
                        ps.setDouble(2, book.getPrice());
                        ps.setInt(3, book.getId());
                    }

                    // 获取批量更新的条数
                    @Override
                    public int getBatchSize() {
                        return books.size();
                    }
                });

//        return jdbcTemplate.batchUpdate("UPDATE books set title=?, price=? WHERE id =?", new BatchPreparedStatementSetter() {
//            @Override
//            public void setValues(PreparedStatement ps, int i) throws SQLException {
//                Book book = books.get(i);
//                ps.setString(1, book.getTitle());
//                ps.setBigDecimal(2, new BigDecimal(book.getPrice() + ""));
//                ps.setInt(3, book.getId());
//
//            }
//
//            @Override
//            public int getBatchSize() {
//                return books.size();
//            }
//        });
    }

}
